package com.neuronbit.businessflow.flow.source;

import com.neuronbit.javaparser.ast.CompilationUnit;
import com.neuronbit.javaparser.ast.PackageDeclaration;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * The interface Generated source.
 */
public interface JavaSource {

    /**
     * Write java source file.
     *
     * @param outputPath the output path
     * @throws IOException the io exception
     */
    default void writeJavaSourceFile(Path outputPath) throws IOException {
        CompilationUnit compilationUnit = getCompilationUnit();
        if (compilationUnit == null) {
            return;
        }
        Path resolve = outputPath;
        Optional<PackageDeclaration> packageDeclaration = compilationUnit.getPackageDeclaration();
        if (packageDeclaration.isPresent()) {
            String packageName = packageDeclaration.get().getName().asString();
            for (String string : packageName.split("\\.")) {
                resolve = resolve.resolve(string);
            }
        }
        String fileName = getFileName();
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("File name cannot be blank for source ");
        }
        if (!fileName.endsWith(".java")) {
            fileName += ".java";
        }
        compilationUnit.setStorage(resolve.resolve(fileName), UTF_8);
        compilationUnit.getStorage().get().save();
    }

    /**
     * Generate.
     *
     * @throws ClassNotFoundException the class not found exception
     * @throws NoSuchMethodException  the no such method exception
     */
    void generate() throws ClassNotFoundException, NoSuchMethodException;

    /**
     * Gets compilation unit.
     *
     * @return the compilation unit
     */
    CompilationUnit getCompilationUnit();

    /**
     * Gets file name.
     *
     * @return the file name
     */
    String getFileName();

}
